from rest_framework import serializers
from submission.models.submission_model import SubmissionModel
from django.utils import timezone
from datetime import datetime


class SubmissionCreateSerializer(serializers.Serializer):
    """提交代码序列化器"""
    problem = serializers.IntegerField(required=True, help_text="题目ID")
    language = serializers.IntegerField(required=True, help_text="语言类型")
    code = serializers.CharField(required=True, help_text="代码内容")

    def validate_language(self, value):
        """验证语言类型"""
        valid_languages = [0, 1, 3]  # C, C++, Python
        if value not in valid_languages:
            raise serializers.ValidationError("不支持的语言类型")
        return value

    def validate_code(self, value):
        """验证代码内容"""
        if not value or len(value.strip()) == 0:
            raise serializers.ValidationError("代码内容不能为空")
        if len(value) > 65535:  # 限制代码长度
            raise serializers.ValidationError("代码长度超出限制")
        return value.strip()


class SubmissionSerializer(serializers.ModelSerializer):
    """提交记录序列化器"""
    status = serializers.SerializerMethodField()
    status_display = serializers.CharField(source='get_status_display')
    status_class = serializers.SerializerMethodField()
    language_display = serializers.CharField(source='get_language_display')
    problem_title = serializers.CharField(source='problem.title')
    time_display = serializers.SerializerMethodField()
    memory_display = serializers.SerializerMethodField()
    submit_time = serializers.SerializerMethodField()
    username = serializers.CharField(source='user.username')
    nick_name = serializers.CharField(source='user.nick_name')

    class Meta:
        model = SubmissionModel
        fields = [
            'id',
            'status',
            'status_display',
            'status_class',
            'problem_title',
            'language_display',
            'time_display',
            'memory_display',
            'submit_time',
            'code',
            'compile_output',
            'test_cases_passed',
            'total_test_cases',
            'username',
            'nick_name',
        ]

    def get_status(self, obj):
        """获取状态码"""
        return obj.result

    def get_status_class(self, obj):
        """获取状态对应的样式类"""
        status_map = {
            0: 'warning',      # 未提交
            1: 'warning',   # 等待评测
            2: 'info',   # 评测中
            3: 'success',     # 通过
            4: 'error',     # 答案错误
            5: 'error',     # 编译错误
            6: 'error',    # 运行时错误
            7: 'error',   # 时间超限
            8: 'error',     # 内存超限
            9: 'error',     # 系统错误
        }
        return status_map.get(obj.result, 'info')

    def get_time_display(self, obj):
        """格式化运行时间"""
        if obj.time_used is None:
            return '---'
        return f"{obj.time_used}ms"

    def get_memory_display(self, obj):
        """格式化内存使用"""
        if obj.memory_used is None:
            return '---'
        if obj.memory_used < 1024:
            return f"{obj.memory_used}KB"
        return f"{obj.memory_used / 1024:.1f}MB"

    def get_submit_time(self, obj):
        """格式化提交时间"""
        if not obj.create_time:
            return '---'
        
        now = timezone.now()
        diff = now - obj.create_time
        
        if diff.days > 0:
            return obj.create_time.strftime('%Y-%m-%d %H:%M')
        elif diff.seconds >= 3600:
            hours = diff.seconds // 3600
            return f"{hours}小时前"
        elif diff.seconds >= 60:
            minutes = diff.seconds // 60
            return f"{minutes}分钟前"
        else:
            return "刚刚"